import pygame
import sys
import os
from UI.battle_ui import BattleUI
from UI.button import Button
from UI.enter_ui import EnterUI
from UI.select_charactor_ui import CharacterSelectUI
from UI.map_ui import MapUI

from data.attribute_restraint import Attribute
from data.equipment import create_equipment
from data.champion import Champion, create_player, create_skill, create_enemy
from function.battle import Battle
from constant import Setting  # 导入设置类

def main():
    # 初始化Pygame
    pygame.init()
    setting = Setting()  # 创建设置实例
    screen = pygame.display.set_mode((setting.screen_width, setting.screen_height))
    pygame.display.set_caption(setting.screen_title)
    clock = pygame.time.Clock()

    # 创建测试技能
    skill_data = create_skill()

    # 创建测试装备
    equipment_data = create_equipment()

    # 创建测试角色（2个可选角色）
    character_data = create_player()

    # 创建测试敌人（战斗用）
    enemy_data = create_enemy()

    # 1. 运行开始界面
    enter_ui = EnterUI()
    enter_ui.run()

    # 2. 运行角色选择界面
    select_ui = CharacterSelectUI([character for character in character_data.values()])
    selected_char = select_ui.run()
    if not selected_char:
        print("未选择角色，程序退出")
        return

    # 3. 运行地图界面
    map_ui = MapUI(selected_char)

    def show_congratulations():
        # 重新初始化显示窗口（确保窗口有效）
        screen = pygame.display.set_mode((setting.screen_width, setting.screen_height))
        pygame.display.set_caption(setting.screen_title)  # 重置窗口标题
        current_dir = os.path.dirname(os.path.abspath(__file__))

        # ---------------------- 新增：加载窗口背景图 ----------------------
        background_img = None
        try:
            # 从配置中获取背景图路径（需在constant.py中添加"congrats_bg"配置）
            bg_path = os.path.join(current_dir, setting.images_path["intro_background"])
            background_img = pygame.image.load(bg_path).convert()
            # 缩放背景图适配窗口尺寸
            background_img = pygame.transform.scale(
                background_img, 
                (setting.screen_width, setting.screen_height)
            )
        except FileNotFoundError:
            print(f"【警告】未找到祝贺界面背景图，使用默认颜色背景")
        except KeyError:
            print(f"【警告】请在constant.py的images_path中添加'congrats_bg'配置")

        # 加载隐藏角色图片
        try:
            path = os.path.join(current_dir, setting.images_path["hiden_charactor"])
            hiden_char_img = pygame.image.load(path).convert_alpha()
        except FileNotFoundError:
            print(f"【错误】未找到隐藏角色图片：{setting.images_path['hiden_charactor']}")
            # 用默认色块替代
            hiden_char_img = pygame.Surface((200, 300), pygame.SRCALPHA)
            hiden_char_img.fill((255, 215, 0, 200))  # 金色半透明块

        # 调整图片大小（保持比例）
        img_width, img_height = hiden_char_img.get_size()
        scale = min(setting.screen_width * 0.6 / img_width, setting.screen_height * 0.6 / img_height)
        hiden_char_img = pygame.transform.scale(
            hiden_char_img, 
            (int(img_width * scale), int(img_height * scale))
        )

        # 计算图片位置（居中显示）
        img_x = (setting.screen_width - hiden_char_img.get_width()) // 2
        img_y = (setting.screen_height - hiden_char_img.get_height()) // 3

        # ---------------------- 新增：创建人物后的透明灰色背景 ----------------------
        # 灰色背景大小比人物大一圈（上下左右各加30像素）
        bg_padding = 30
        char_bg_width = hiden_char_img.get_width() + bg_padding * 2
        char_bg_height = hiden_char_img.get_height() + bg_padding * 2
        char_bg = pygame.Surface((char_bg_width, char_bg_height), pygame.SRCALPHA)
        # 填充透明灰色（RGBA：180,180,180是浅灰色，128是透明度）
        char_bg.fill((180, 180, 180, 128))
        # 计算灰色背景位置（与人物居中对齐）
        char_bg_x = img_x - bg_padding
        char_bg_y = img_y - bg_padding

        # 创建祝贺文字
        try:
            congrat_text = setting.font_title.render("Congratulations!", True, setting.color_yellow)
        except:
            # 字体加载失败时用默认字体
            congrat_text = pygame.font.SysFont("SimHei", 64).render("Congratulations!", True, (255, 215, 0))
        text_x = (setting.screen_width - congrat_text.get_width()) // 2
        text_y = img_y + hiden_char_img.get_height() + 30  # 图片下方30像素

        # 显示循环
        running = True
        while running:
            # 1. 绘制窗口背景图（优先使用图片，否则用默认颜色）
            if background_img:
                screen.blit(background_img, (0, 0))
            else:
                screen.fill((40, 40, 60))  # 深色背景 fallback

            # 2. 绘制人物后的透明灰色背景（在人物下方）
            screen.blit(char_bg, (char_bg_x, char_bg_y))

            # 3. 绘制隐藏角色图片（在灰色背景上方）
            screen.blit(hiden_char_img, (img_x, img_y))

            # 4. 绘制祝贺文字
            screen.blit(congrat_text, (text_x, text_y))

            # 事件处理（点击任意键或关闭窗口退出）
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                    pygame.quit()
                    sys.exit()
                if event.type == pygame.KEYDOWN or event.type == pygame.MOUSEBUTTONDOWN:
                    running = False

            pygame.display.flip()
            clock.tick(setting.fps)

    # 定义战斗跳转逻辑（适配逃跑）
    def battle_jump(level_num, player):
        # 进入战斗界面
        enemy = enemy_data[level_num]
        battle = Battle(player, enemy)
        battle.winner = None  # 初始化战斗胜利者
        
        if player.check_level(level_num):
            while battle.winner is None:
                battle.start_battle()
                battle_ui = BattleUI(player, enemy_data[level_num], battle)
                battle_ui.run()  # 战斗UI运行

                # 检查是否逃跑（现在视为输掉战斗）
                if battle.winner == enemy:  # 如果敌人是胜利者
                    battle_log = [f"战斗结束：{player.name}输掉了战斗！"]
                    break  # 退出战斗循环
        
        # 检查是否达到最高等级，如果是则显示隐藏角色和祝贺信息
        if player.check_max_level():
            show_congratulations()
            
        # 胜利时已在Battle.end_battle中自动获取装备
        map_ui.running = True
        map_ui.equipments = player.equipment_deck  # 刷新地图界面的装备列表
        map_ui.inventory_elements = map_ui._init_inventory_elements()  # 重新初始化装备槽
        map_ui.run()
        
    map_ui.set_battle_jump(battle_jump)
    map_ui.run()

if __name__ == "__main__":
    main()